﻿using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;

namespace HYIndicateDimension.DrawLaneLine
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	internal class CmdDrawLaneLegend : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (Convert.ToInt16(commandData.Application.Application.VersionNumber) < 2016)
			{
				YJKMessageBox.Show("此功能不支持当前的Revit版本");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			UIApplication application = commandData.Application;
			Document document = application.ActiveUIDocument.Document;
			Autodesk.Revit.DB.View activeView = document.ActiveView;
			if ((int)activeView.ViewType == 4 || (int)activeView.ViewType == 6)
			{
				YJKMessageBox.Show("此功能不支持当前视图！");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Transaction transaction = new Transaction(document, "createLegend");
			try
			{
				transaction.Start();
				string fsName = "车道线箭头";
				string text = "";
				FamilySymbol familySymbolByName = YJKRevitTools.GetFamilySymbolByName("LaneLegend", fsName, document, ref text);
				if (familySymbolByName == null)
				{
					YJKMessageBox.Show("没有找到车道线箭头族！");
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				if (!familySymbolByName.IsActive)
				{
					familySymbolByName.Activate();
				}
				transaction.Commit();
				try
				{
					application.ActiveUIDocument.PromptForFamilyInstancePlacement(familySymbolByName);
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException)
				{
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				catch (Exception ex)
				{
					YJKMessageBox.Show(ex.Message);
				}
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void DrawEntranceLineTabel(Autodesk.Revit.DB.Document doc, XYZ position)
		{
			string fsName = "车道线箭头";
			Transaction transaction = new Transaction(doc, "createLegend");
			try
			{
				transaction.Start();
				string text = "";
				FamilySymbol familySymbolByName = YJKRevitTools.GetFamilySymbolByName("LaneLegend", fsName, doc, ref text);
				if (familySymbolByName == null)
				{
					transaction.RollBack();
				}
				else
				{
					if (!familySymbolByName.IsActive)
					{
						familySymbolByName.Activate();
					}
					doc.Create.NewFamilyInstance(position, familySymbolByName, doc.ActiveView);
					transaction.Commit();
				}
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
		}
	}
}
